<?php

class Petshop_controller extends Controller {
//declares static variables containing error messages
    private static $submit_error = "Unfortunately your form was entered incorrectly";
    private static $success = "You submission was a success";

//controller creates instantiates class
    function Petshop_controller() {
        parent::Controller();

        //loading my libraries
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->helper('recaptcha');
        
        $this->load->model('db_access');

    }

//sends raw http:// header as an initial redirect so that all urls work
    function index() {

        header( 'Location: http://2007.ispace.ci.fsu.edu/~jdw08e/LIS4368/Pet_Shop/index.php/petshop_controller/display_pet_list' ) ;
    }

//displays the validation message view
    function display_validation_message($message, $trigger) {

        $data['message'] = $message;

        //conditional statements determine the page to load
        if ($trigger == "updatepage") {
            $data['address'] = "display_site_update";
        }
        elseif ($trigger == "loginpage") {
            $data['address'] = "display_admin_login";
        }
        else {
            $data['address'] = "display_pet_list";
        }

        $this->load->view('validation_message', $data);
    }

    //displays the search results page
function display_search_results() {

        $searchstring = $this->input->post('search_string_input');
//declares array variable from model
        $pets['pets'] = $this->db_access->load_selected_pets($searchstring);

        $this->load->view('search_results', $pets);
    }

//displayes siteupdate page
    function display_site_update() {
        //checks if user is logged in
        if($this->session->userdata('login_name')== null) {

            $this->display_admin_login();

        }
        else {

            $data['about'] = $this->db_access->load_about_us();
            $data['pets'] = $this->db_access->load_pets();

            $this->load->view('site_update', $data);

        }
    }

// passed about us info to model and loads site_update view
    function edit_about_us() {
        
        $about_us = $this->input->post('about_us_input');

        $this->db_access->save_about_us($about_us);

        $this->display_site_update();
    }


    function display_pet_list() {
//loads pet records from database using the model
        $pets['pets'] = $this->db_access->load_pets();
//loads pet_list view and sends with it the pets array
        $this->load->view('pet_list', $pets);
    }

//displays about us view
    function display_about_us() {

        $data['about'] = $this->db_access->load_about_us();

        $this->load->view('about_us', $data);
    }

//displays login view
    function display_admin_login() {
        $this->load->view('admin_login');
    }


    function display_pet_details() {

        $petname= $this->input->post('name_input');
//loads pet records from database using the model
        $petdata['pet'] = $this->db_access->load_pet($petname);
//loads pet_list view and sends with it the pets array
        $this->load->view('pet_details', $petdata);
    }

    function display_edit_pet() {

        //checks if user is logged in
        if($this->session->userdata('login_name')== null) {

            $this->display_admin_login();
        }
        else {
            $petname = $this->input->post('pet_name_list');
//loads pet records from database using the model
            $petdata['pet'] = $this->db_access->load_pet($petname);
//loads pet_list view and sends with it the pets array
            $this->load->view('edit_pet', $petdata);
        }
    }

    function display_add_pet() {
        //checks if user is logged in
        if($this->session->userdata('login_name')== null) {

            $this->display_admin_login();

        }
        else {
            $this->load->view('add_pet');
        }
    }

//function handles adding, editing, and deleting pet records as well as image uploads
function add_edit_delete_pet() {

        $i = 0;
        $petarray;
        $picname1="";
        $picname2="";
        //saves path to image directory
        $path = getcwd()."/system/application/images/";

        $button = $this->input->post('button');
//loop iterates through the $_FILES array
        foreach ($_FILES["pic_input"]["error"] as $key => $error ) {

            // if the upload is successful
            if ($error == UPLOAD_ERR_OK) {

                $i++;
                //sets variable equal to array values
                $tmp_name = $_FILES["pic_input"]["tmp_name"][$key];
                $name = $_FILES["pic_input"]["name"][$key];
		$type = $_FILES["pic_input"]["type"][$key];

//image validation, checks if the file is an image
if ($type == 'image/pjpeg' || $type == 'image/jpeg' || $type == 'image/jpg' || $type == 'image/gif' || $type == 'image/png'){
      
    //moves file from temprary directory tp permanent directory
    move_uploaded_file($tmp_name,$path.$name);

//selects variable name based of incremented variable, and declares picname equal to uploaded file name
                if($i == 1) {
                    $picname1 = $name;
                }
                else {
                    $picname2 = $name;
                }
            }
        }
}
//sets the rules for form validation
        $this->form_validation->set_rules('name_input', 'Name', 'trim|required|max_length[40]');
        $this->form_validation->set_rules('species_input', 'Species', 'trim|required|max_length[45]');
        $this->form_validation->set_rules('breed_input', 'Breed', 'trim|required|max_length[45]');
        $this->form_validation->set_rules('descript_input', 'Descript', 'trim|required|max_length[300]');
        $this->form_validation->set_rules('notes_input', 'Notes', 'trim|required|max_length[300]');

        //runs the form validator
        $result = $this->form_validation->run();

        if ($result == FALSE) {
            //if validation fails, display error message
            $this->display_validation_message(self::$submit_error, 'updatepage');

        }
        else {
            //conditional statements determine which array to use based on which file upload was use
            if($picname1 == "" && $picname2 == ""){

                $petarray = array('name' => $this->input->post('name_input'), 'species' => $this->input->post('species_input'),
                    'breed' => $this->input->post('breed_input'),'descript' => $this->input->post('descript_input'),
                    'notes' => $this->input->post('notes_input')); 
            }
            elseif($picname1 == "" && $picname2 != ""){

                $petarray = array('name' => $this->input->post('name_input'), 'species' => $this->input->post('species_input'),
                    'breed' => $this->input->post('breed_input'),'descript' => $this->input->post('descript_input'),
                    'notes' => $this->input->post('notes_input'),'pic2' => $picname2);
            }
            elseif($picname1 != "" && $picname2 == ""){

                $petarray = array('name' => $this->input->post('name_input'), 'species' => $this->input->post('species_input'),
                    'breed' => $this->input->post('breed_input'),'descript' => $this->input->post('descript_input'),
                    'notes' => $this->input->post('notes_input'), 'pic1' => $picname1);
            }
            else{

                $petarray = array('name' => $this->input->post('name_input'), 'species' => $this->input->post('species_input'),
                    'breed' => $this->input->post('breed_input'),'descript' => $this->input->post('descript_input'),
                    'notes' => $this->input->post('notes_input'), 'pic1' => $picname1, 'pic2' => $picname2);
            }
        }
//these conditional statements determine what to do with the array based on which button submitted the form
            if ($button == "Delete Record") {
                
                $this->db_access->remove_pet($this->input->post('pet_id_input'));
                $this->display_validation_message(self::$success, 'updatepage');
            }
            elseif($button == "Edit Record") {
                
                $this->db_access->edit_pet($petarray, $this->input->post('pet_id_input'));

                $this->display_validation_message(self::$success, 'updatepage');
            }
            else {
                $this->db_access->insert_pet($petarray);
                $this->display_validation_message(self::$success, 'updatepage');
            }
            
        }
    

//controls login functionality
    function login() {
     
        //declares form validation rules
      $rules['login_name_input'] = 'required|max_length[20]';
      $rules['password_input'] = 'required|max_length[10]';
      $rules['recaptcha_challenge_field'] = 'required|callback_recaptcha_matches';

  //sets form validation rules
 $this->form_validation->set_rules($rules);
//runs form validation
      $result = $this->form_validation->run();
      //conditional statements determine what action to take
      if($result == FALSE){
          //displays error message if validation fails
          $this->display_validation_message("The supplied login information was incorrect", 'loginpage');

      }
      else{

          $login_name = $this->input->post('login_name_input');
          $password = $this->input->post('password_input');

          //checks login data against database
      if($this->db_access->login_check($login_name, $password) == TRUE) {
//declares session variable containing the logged in users name
          $sessiondata['login_name'] = $login_name;
          $this->session->set_userdata($sessiondata);
          $this->display_site_update();
      }
      else {
          $this->display_validation_message("The supplied login information was incorrect", 'loginpage'); //Indicates password failure

      }
      }
  }

  //controls recaptcha checks
function recaptcha_matches($field){
       $this->config->load('recaptcha');
       $public_key = $this->config->item('recaptcha_public_key');
       $private_key = $this->config->item('recaptcha_private_key');
       $response_field = $this->input->post('recaptcha_response_field');
       $challenge_field = $this->input->post('recaptcha_challenge_field');
       $response = recaptcha_check_answer($private_key,
                                          $_SERVER['REMOTE_ADDR'],
                                          $challenge_field,
                                          $response_field);
       if ($response->is_valid)
       {
           return TRUE;
       }
       else
       {
           $this->form_validation->recaptcha_error = $response->error;
           $this->form_validation->set_message('recaptcha_matches', 'The %s is incorrect. Please try again.');
           return FALSE;
       }

}

//sends an email inquiry about a selected pet
    function enquire() {
//sets validation rules
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('subject', 'Subject', 'trim|required|max_length[70]');
        $this->form_validation->set_rules('message', 'Message', 'trim|required|max_length[400]');
        $rules['recaptcha_challenge_field'] = 'required|callback_recaptcha_matches';
//run form validation
        $result = $this->form_validation->run();

        if ($result == FALSE) {
//displays error message if validation fails
            $this->display_validation_message(self::$submit_error, '');
        }
        else {
            //sends email
            $to = "jdw08e@fsu.edu";
            $subject = $this->input->post('subject');
            $body = $this->input->post('message');

            mail($to, $subject, $body);

            $this->display_validation_message(self::$success, '');
        }
    }
}
/* End of file petshop_controller.php */
/* Location: ./system/application/controllers/petshop.php */